package com.xuyiwei.mayi.service;

import java.io.*;
import java.net.Socket;
import java.util.List;
import java.util.Random;

/**
 * Created by xuyiwei on 2019/4/24.
 */
public class ZkClient {
     public static void main(String[] args) throws IOException {
        ZkClient.sengMsg("发送");
    }

    public static String[] getAddress(){
        org.I0Itec.zkclient.ZkClient zk = new org.I0Itec.zkclient.ZkClient("127.0.0.1:2181", 60000, 1000);
        List<String> zks =  zk.getChildren("/zkSocket");
        Random random = new Random();

        int index= random.nextInt(2);

        System.out.println("-----------------------"+index);
        String path = zks.get(index );
        String address = zk.readData("/zkSocket/"+path);
        String add[] = address.split(":");

        return add;
    }

    public static void sengMsg(String msg) throws IOException {
        String[] add = getAddress();
        Socket socket = new Socket(add[0],Integer.parseInt(add[1]));
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        BufferedReader bf = new BufferedReader(new InputStreamReader(in));
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
        String str = null;
        pw.write("你好接收到信息");

        pw.close();
        bf.close();
        in.close();
        out.close();
        socket.close();
    }
}
